package com.libaoxuan.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.libaoxuan.blog.dao.dos.Archives;
import com.libaoxuan.blog.dao.mapper.*;
import com.libaoxuan.blog.dao.pojo.Article;
import com.libaoxuan.blog.dao.pojo.ArticleBody;
import com.libaoxuan.blog.dao.pojo.ArticleTag;
import com.libaoxuan.blog.dao.pojo.SysUser;
import com.libaoxuan.blog.service.ArticleService;
import com.libaoxuan.blog.service.SysUserService;
import com.libaoxuan.blog.service.TagService;
import com.libaoxuan.blog.service.ThreadService;
import com.libaoxuan.blog.utils.UserThreadLocal;
import com.libaoxuan.blog.vo.ArticleBodyVo;
import com.libaoxuan.blog.vo.ArticleVo;
import com.libaoxuan.blog.vo.Result;
import com.libaoxuan.blog.vo.TagVo;
import com.libaoxuan.blog.vo.params.ArticleParam;
import com.libaoxuan.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    TagService tagService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ArchivesMapper archivesMapper;
    @Autowired
    ArticleBodyMapper articleBodyMapper;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    ThreadService threadService;
    @Autowired
    ArticleTagMapper articleTagMapper;

    /**
     * 分页查询数据库article表
     * @param pageParams
     * @return
     */
    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(), pageParams.getTagId(), pageParams.getYear(), pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));
    }

//    @Override
//    public Result listArticle(PageParams pageParams) {
//        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        if (pageParams.getCategoryId() != null) {
//            wrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
//        }
//        if (pageParams.getTagId() != null) {
//            ArrayList<Long> articleIdList = new ArrayList<>();
//            LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(queryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdList.add(articleTag.getArticleId());
//            }
//            if (articleIdList.size() > 0) {
//                wrapper.in(Article::getId, articleIdList);
//            }
//        }
//        //是否置顶进行排序
//        //wrapper.orderByDesc(Article::getWeight);
//        //按照日前发布日期倒序排
//        wrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, wrapper);
//        List<Article> records = articlePage.getRecords();
//        //数据转移
//        //将数据库查询出的数据包装成articlevo类的格式，便于与前端进行交互
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//        return Result.success(articleVoList);
//    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        ArrayList<ArticleVo> articleVoArrayList = new ArrayList<>();
        for (Article record : records) {
            articleVoArrayList.add(copy(record, isTag, isAuthor,false,false));
        }
        return articleVoArrayList;
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory) {
        ArrayList<ArticleVo> articleVoArrayList = new ArrayList<>();
        for (Article record : records) {
            articleVoArrayList.add(copy(record, isTag, isAuthor, isBody, isAuthor));
        }
        return articleVoArrayList;
    }

    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory ) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有接口 都需要标签 作者信息
        if (isTag) {
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(this.findArticleBodyById(article.getBodyId()));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(article.getCategoryId()));
        }
        return articleVo;
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getViewCounts);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit " + limit);
        //select id,title from Article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(wrapper);

        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getCreateDate);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = archivesMapper.listArchives();
        return Result.success(archivesList);
    }

    @Override
    public ArticleVo findArticleById(Long id) {
        /**
         * 根据id查询文章信息
         * 根据bodyId和categoryId关联查询
         */
        Article article = articleMapper.selectById(id);
        //查看完文章，新增阅读数
        //查看完文章后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其它的读操作，性能就会比较低
        //更新增加了此次接口的耗时，如果一旦更新出现问题，不能影响查看文章的操作
        /**
         * 线程池  可以把更新操作扔到线程池中去执行，和主线程就不相关了
         */
        threadService.updateViewCount(articleMapper,article);
        return copy(article,true,true,true,true);
    }

    public ArticleBodyVo findArticleBodyById(Long articleId) {
        QueryWrapper<ArticleBody> wrapper = new QueryWrapper<>();
        wrapper.eq("id", articleId);
        ArticleBody articleBody = articleBodyMapper.selectOne(wrapper);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口要加入到登录拦截器当中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id 当前的登录用户
         * 3. 标签 要将标签加入到关联列表当中
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd"));
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        //插入之后会生成一个文章id
        this.articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(tag.getId());
                this.articleTagMapper.insert(articleTag);
            }
        }
        //articlebody
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(article.getId());
        return Result.success(articleVo);
    }
}
